package com.yvon.service.demo.test.netty00;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 简单客户端
 *
 * @author Yvon
 * @date 2023-10-11
 */
@Slf4j
public class SimpleClient {
    public static void main(String[] args) throws IOException {
        // 得到客户端的channel
        SocketChannel socketChannel = SocketChannel.open();
        // 设置非阻塞
        socketChannel.configureBlocking(false);
        // 得到selector
        Selector selector = Selector.open();
        // 把客户端channel注册到selector上
        SelectionKey selectionKey = socketChannel.register(selector, 0);
        // 设置事件
        selectionKey.interestOps(SelectionKey.OP_CONNECT);
        // 客户端的channel连接服务端
        socketChannel.connect(new InetSocketAddress(8080));
        // 开始轮训事件
        while (true) {
            // 无事件时则阻塞
            selector.select();
            // 得到事件的key
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                // 如果是连接成功事件
                if (key.isConnectable()) {
                    if (socketChannel.finishConnect()) {
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        log.info("已经注册了读事件！");
                        // 向服务的发送一条消息
                        socketChannel.write(ByteBuffer.wrap("客户端发送成功了".getBytes()));
                    }
                }
                // 如果是读事件
                if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    // 分配缓冲区来接收服务端发送来的数据
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    // 向buffer里写数据
                    int len = channel.read(buffer);
                    byte[] readByte = new byte[len];
                    buffer.flip();
                    buffer.get(readByte);
                    log.info("读取到服务端传来的数据：" + new String(readByte));
                }
            }
        }

    }
}
